import json

import pandas as pd
from pymongo import MongoClient
from pprint import pprint


# 连接到 MongoDB
client = MongoClient('localhost', 27017)
db = client['big_data']
collection = db['cars_data']

result=collection.find({})
print(result)
for i in result:
    pprint(i)



# import requests

#
# headers = {
#     "accept": "*/*",
#     "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
#     "cache-control": "no-cache",
#     "pragma": "no-cache",
#     "priority": "u=1, i",
#     "referer": "https://www.dongchedi.com/sales",
#     "sec-ch-ua": "\"Microsoft Edge\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
#     "sec-ch-ua-mobile": "?0",
#     "sec-ch-ua-platform": "\"Windows\"",
#     "sec-fetch-dest": "empty",
#     "sec-fetch-mode": "cors",
#     "sec-fetch-site": "same-origin",
#     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
# }
#
# url = "https://www.dongchedi.com/motor/pc/car/rank_data"
# params = {
#     "aid": "1839",
#     "app_name": "auto_web_pc",
#     "city_name": "长沙",
#     "count": "10",
#     "offset": "10",
#     "month": "",
#     "new_energy_type": "",
#     "rank_data_type": "11",
#     "brand_id": "",
#     "price": "",
#     "manufacturer": "",
#     "outter_detail_type": "",
#     "nation": "0"
# }
# response = requests.get(url, headers=headers,params=params)
#
# print(response.text)
# print(response)



# if __name__ == '__main__':
    # with open("sorted_data.json", "r", encoding="utf-8") as f:
    #     json_data = json.load(f)
    # df = pd.DataFrame(json_data)
    #
    # # 按 'rank' 列进行排序
    # sorted_data = df.sort_values(by='rank')
    # sorted_data_dict = sorted_data.to_dict('records')
    #
    # big_screen_data = DataAnalysis().analysis(sorted_data=sorted_data, sorted_data_dict=sorted_data_dict)
    # print(big_screen_data)
#
#     # print(str(time.time())[:10])
#
#     ana_obj = DataAnalysis()
#     data = ana_obj.analysis(sorted_data, sorted_data_dict)
#
#     print(data)

# 统计每个品牌的车型数量
# brand_counts = df['brand'].value_counts().idxmax()
# # 找出车型最多的品牌
# most_models_brand = brand_counts.idxmax()
# most_models_count = brand_counts.max()
# print(brand_counts)
# 销售最多车型
# max_sale_car = sorted_data.nlargest(1, 'saleVolume')['carModel'].iloc[0]
# 车型最多品牌
# max_car_model = sorted_data.nlargest(1, 'carModel')['brand'].iloc[0]
# print(max_car_model )
# big_screen_data=data_analysis.DataAnalysis(sorted_data,sorted_data_dict)
# print(big_screen_data)


# print(df.nlargest(1, 'saleVolume')['carModel'].iloc[0])
# max_prices = df['price'].apply(lambda x: x['min']).mean()
# brand_counts = df['brand'].value_counts()
# sorted_brand_counts = brand_counts.sort_values(ascending=False).to_json(force_ascii=False)

# 筛选新能源汽车
# new_energy_cars = df[df['energyType'].isin(['纯电动', '插电式混合动力', '增程式'])]
# # 按销量排序
# sorted_new_energy_cars = new_energy_cars.sort_values(by='saleVolume', ascending=False)[['carName', 'saleVolume','energyType']]
#
# res=sorted_new_energy_cars.to_json(orient='records', force_ascii=False)

# cars_brand_sale_rank=df['brand'].value_counts().sort_values(ascending=False).to_json(force_ascii=False)
# print(cars_brand_sale_rank)
# sales_summary = df.groupby('brand')['saleVolume'].sum().reset_index()
# sales_summary=sales_summary.to_json(orient='records', force_ascii=False)
# print(sales_summary)

# 计算每辆车的价格范围
# df['averagePrice'] = df['price'].apply(lambda x: (x['min'] + x['max']) / 2)
# # 定义价格区间
# bins = [0, 5, 10, 20, 30, float('inf')]
# labels = ['0-5万', '5-10万', '10-20万', '20-30万', '30万以上']
# # 将价格分组
# df['priceGroup'] = pd.cut(df['averagePrice'], bins=bins, labels=labels, right=False)
# # 统计每个价格区间的数量
# price_distribution = df['priceGroup'].value_counts().sort_index().to_dict()

# 将结果转换为字典格式
# result = {
#     "totalCars": len(df),
#     "priceDistribution": price_distribution.to_dict()
# }
#
# # 转换为 JSON 格式
# json_result = json.dumps(result, ensure_ascii=False, indent=4)
#
# # 输出 JSON
# print(price_distribution.to_dict())
# json.dump(price_distribution)
# print(res)
# # cars=df[['carName', 'brand']]
# result = df.apply(lambda row: f"{row['brand']} {row['carName']}", axis=1)
# # 将结果转换为字符串
# result_string = ' '.join(result)
# print(result_string)
# 词云图
# result = df.apply(lambda row: f"{row['brand']} {row['carName']}", axis=1)
# cars_string = ' '.join(result)
# wordcloud = WordCloud(font_path="static/江城律动宋.ttf",width=800, height=400,
#                       background_color='black').generate(cars_string)
#
# # 保存词云图到本地
# wordcloud.to_file('wordcloud.png')  # 保存为PNG文件
# type_counts = df['energyType'].value_counts()
# total_count = type_counts.sum()
# type_ratios = (type_counts / total_count * 100).round(2)  # 转换为百分比并保留两位小数
#
# # 4. 转换为 JSON 格式，确保中文正常显示
# type_ratios_json = type_ratios.to_json(orient='index', force_ascii=False)
# print(type_ratios_json)
# print(sorted_brand_counts)

# print(max_prices)
# print(df.to_json(orient='records', force_ascii=False))